package com.framework.util;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.framework.entity.DatacenterFormMap;
import com.framework.entity.factory.FormmapFactory;
import com.framework.entity.ClientDatasourceFormMap;
import com.framework.entity.view.UsersourceViewFormMap;
import com.framework.plugin.MapToProperties;
import com.framework.plugin.ReflectHelper;
import com.framework.plugin.test.ContextHolder;
import com.framework.plugin.test.DynamicDataSource;
import com.framework.util.datasource.JDBCSource;
import com.framework.util.shell.CreateDBBuilder;


public class GetDataFromOtherDB {
	private static DynamicDataSource dataSource;
	private static HashMap<String, JDBCSource> hashMap;

	public static DynamicDataSource getDataSource() {
		return dataSource;
	}


	public static HashMap<String, JDBCSource> getHashMap() {
		return hashMap;
	}


	/**
	 * 到A裤，取得用户数据库数据，并且切换
	 * 
	 * @param username
	 * @param password
	 * @param request
	 * @throws Exception
	 */
	public static JDBCSource connect2dbFormMap(DatacenterFormMap datacenterFormMap) throws Exception {
		// TODO Auto-generated method stub
		if (dataSource != null || hashMap != null) {
		} else {
			dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
			hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource, "resolvedDataSources");
		}
		JDBCSource jdbcTest = new JDBCSource();
		jdbcTest.changeJDBC(datacenterFormMap);
		hashMap.put(datacenterFormMap.get("fathername").toString(), jdbcTest);
		ContextHolder.setCustomerType(datacenterFormMap.get("fathername").toString());
		return jdbcTest;
	}

	/**
	 * 到A裤，取得用户数据库数据，并且切换
	 * 
	 * @param username
	 * @param password
	 * @param request
	 * @throws Exception
	 */
	public static void getDataFromA(String username, String password) throws Exception {
		// TODO Auto-generated method stub
		// 到A裤，取得用户数据库数据
		if (username.equals("admin")) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		} else {
			UsersourceViewFormMap usersourceViewFormMap = new UsersourceViewFormMap();
			usersourceViewFormMap.put("username", username);
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();

			if (usersourceViewFormMap.containsKey("client_id")) {
				JDBCSource jdbcTest = new JDBCSource();
				Properties properties = MapToProperties.map2properties(usersourceViewFormMap);
				jdbcTest.changeJDBC(properties);
				dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
				hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource,
						"resolvedDataSources");
				hashMap.put(username, jdbcTest);
				System.out.println(ReflectHelper.getFieldByFieldName(dataSource, "targetDataSources"));

				ContextHolder.setCustomerType(username);

			} else {
				ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			}
		}
	}

	/**
	 * 根据传入的usersourceViewFormMap，进行数据源的切换
	 *	@author 李品良
	 * @param usersourceViewFormMap
	 * @throws Exception
	 */
	public static void switchDataSource(UsersourceViewFormMap usersourceViewFormMap) throws Exception {
		// TODO Auto-generated method stub
		// 到A裤，取得用户数据库数据
		String cellphone = usersourceViewFormMap.get("cellphone").toString();
		String db_name = usersourceViewFormMap.get("db_name").toString();
		if (usersourceViewFormMap.containsKey("client_id")) {
			JDBCSource jdbcTest = new JDBCSource();
			Properties properties = MapToProperties.map2properties(usersourceViewFormMap);
			jdbcTest.changeJDBC(properties);
			dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
			hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource, "resolvedDataSources");
			hashMap.put(cellphone+db_name, jdbcTest);
			ContextHolder.setCustomerType(cellphone+db_name);
		} else {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		}
	}
	
	public static void switchDataSource() {
		// TODO
		Subject subject=SecurityUtils.getSubject();
		if (subject!=null) {
			Session session=subject.getSession();
			DatacenterFormMap datacenterFormMap = (DatacenterFormMap) session.getAttribute(session.getId());
			JDBCSource jdbcTest=(JDBCSource) session.getAttribute("jdbcTest");
			if (datacenterFormMap != null) {
				String cellphone = (String) datacenterFormMap.get("cellphone");
				if (cellphone != null) {
					if (cellphone.equals("admin")) {
						ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
						return ;
					} else {
						String db_name=jdbcTest.getUrl();
						int index=db_name.lastIndexOf("/");
						db_name=db_name.substring(index+1);
						ContextHolder.setCustomerType(cellphone+db_name);
						return ;
					}
				}
			}else {
				ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			}
		}
	}
	
	/**
	 * 
	 * @param userId
	 * @return
	 */
	public static DatacenterFormMap getDataCenterviaID(String userId) {
		DatacenterFormMap datacenterFormMap = new DatacenterFormMap();
		datacenterFormMap.put("id", userId);
		datacenterFormMap = datacenterFormMap.findbyFrist();
		return datacenterFormMap;
	}

	public static void name() {

	}

	public static void getUserMapFromA() {

	}

	@SuppressWarnings("unchecked")
	public static void getDataFromA(String cellphone, String password, HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		// 到A裤，取得用户数据库数据
		if (cellphone.contains("admin")) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		} else {
			UsersourceViewFormMap usersourceViewFormMap = new UsersourceViewFormMap();
			usersourceViewFormMap.put("cellphone", cellphone);
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();

			HttpSession session = request.getSession();
			if (usersourceViewFormMap != null) {
				session.setAttribute(cellphone, usersourceViewFormMap);
				JDBCSource jdbcTest = new JDBCSource();
				Properties properties = MapToProperties.map2properties(usersourceViewFormMap);
				jdbcTest.changeJDBC(properties);
				dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
				hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource,
						"resolvedDataSources");
				hashMap.put(cellphone, jdbcTest);
				System.out.println(ReflectHelper.getFieldByFieldName(dataSource, "targetDataSources"));

				ContextHolder.setCustomerType(cellphone);

			} else {
				ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static boolean getDataFromCellphone(String cellphone, String db_name, HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		// 到A裤，取得用户数据库数据
		if (cellphone.contains("admin")) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		} else {
			UsersourceViewFormMap usersourceViewFormMap = FormmapFactory.getBeanFormMap(UsersourceViewFormMap.class);
			usersourceViewFormMap.put("cellphone", cellphone);
			usersourceViewFormMap.put("db_name", db_name);
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();

			HttpSession session = request.getSession();
			if (usersourceViewFormMap != null) {
				session.setAttribute(cellphone+db_name, usersourceViewFormMap);
				JDBCSource jdbcTest = new JDBCSource();
				Properties properties = MapToProperties.map2properties(usersourceViewFormMap);
				jdbcTest.changeJDBC(properties);
				dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
				hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource,
						"resolvedDataSources");
				hashMap.put(cellphone+db_name, jdbcTest);

				ContextHolder.setCustomerType(cellphone+db_name);
				return true;
			} else {
				ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
				return false;
			}
		}
		return false;
		
	}
	
	
	@SuppressWarnings("unchecked")
	public static boolean getDataFromCellphoneAdd(String cellphone, String db_name, HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		// 到A裤，取得用户数据库数据
		if (cellphone.contains("admin")) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		} else {
			UsersourceViewFormMap usersourceViewFormMap = FormmapFactory.getBeanFormMap(UsersourceViewFormMap.class);
			usersourceViewFormMap.put("cellphone", cellphone);
			usersourceViewFormMap.put("db_name", db_name);
			usersourceViewFormMap.put("level", 1);
			usersourceViewFormMap.put("status", 0);
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();
			
			Session session = Common.getUserSession();
			if (usersourceViewFormMap != null) {
				session.setAttribute(cellphone+db_name, usersourceViewFormMap);
				JDBCSource jdbcTest = new JDBCSource();
				Properties properties = MapToProperties.map2properties(usersourceViewFormMap);
				jdbcTest.changeJDBC(properties);
				@SuppressWarnings("unused")
				Connection connection=jdbcTest.getConnection();//这是一个检验值
				if (dataSource==null||hashMap==null) {
					dataSource = (DynamicDataSource) SpringFactory.getObject("dynamicDataSource");
					hashMap = (HashMap<String, JDBCSource>) ReflectHelper.getValueByFieldName(dataSource,
							"resolvedDataSources");
				}
				hashMap.put(cellphone+db_name, jdbcTest);
				ContextHolder.setCustomerType(cellphone+db_name);
				return true;
			} else {
				ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
				return false;
			}
		}
		return false;
		
	}
}
